#!/bin/sh
# postinst framework for openpanel packages
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
#

case "$1" in
    configure)
mkdir -p /var/opencore/conf/staging/MySQL
chown opencore:authd /var/opencore/conf/staging/MySQL
if [ ! -e /etc/openpanel/mysql.pwd ]; then
# Check if the mysql user has already been created
# Get the debian sys-maint password
DEB_SYSPW=$(awk '/password = */ {password = $3} END {print password}' /etc/mysql/debian.cnf)

# The openpanel user's passsword, this has to be autogenerated
OP_UPW=$(head -c 12 /dev/urandom | uuencode -m - | head -n 2 | tail -n 1)

MYSQL_QRY="INSERT INTO mysql.user(Host,User,Password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Reload_priv,Shutdown_priv,Process_priv,File_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Show_db_priv,Super_priv,Execute_priv,Create_tmp_table_priv,Lock_tables_priv,Create_user_priv) VALUES ('localhost','openpanel',password('$OP_UPW'),'y','y','y','y','y','y','y','y','y','y','y','y','y','y','y','y','y','y','y','y');"

# Check if the mysql server is running, if not
# we have to start it
invoke-rc.d mysql restart

if [ ! -e /etc/openpanel/mysql.pwd ]; then
  # exec query in mysql
  echo "Trying to create openpanel user"
  mysql -u debian-sys-maint --password=$DEB_SYSPW -e "$MYSQL_QRY"
  invoke-rc.d mysql restart
  # mysql -u root -e "$MYSQL_QRY"

  if [ "$?" -ne "0" ]; then
        echo "ERROR: Creating openpanel user in mysql database server"
        exit 1
  fi

  # write the new password to /etc/openpanel/mysql.pwd
  # and change the file ops so nobody except root cab read
  # its contents
  if [ ! -d /etc/openpanel ]; then
        mkdir /etc/openpanel
  fi 

  echo "$OP_UPW" > /etc/openpanel/mysql.pwd
  chmod 600 /etc/openpanel/mysql.pwd
fi
fi

    ;;

    abort-upgrade|abort-remove|abort-deconfigure)

    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0


